package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.GeneralRequest.GeneralRequest;
import com.mp.approvalreq.service.GeneralRequestServicePrx;
import com.mp.approvalreq.util.ListHelper;
import com.mp.user.entity.User;
import com.mp.user.service.UserServicePrx;
import com.plusmoney.exception.RpcServerLogicalException;
import com.plusmoney.util.Utils;
import com.qq.tars.client.util.ServantUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 单纯计算审批流
 *
 * @author Administrator
 * <p>
 * {"amount":16800,"project":1,"applicant":"5215"}
 */
@WebServlet("/calcRequestFlow")
public class CalcRequestFlow extends AbstractServlet {

    private static final long serialVersionUID = -6524473373623928868L;

    private static final Logger logger = LoggerFactory.getLogger(CalcRequestFlow.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        try {
            User user = getReqUser(req);

            GeneralRequest dto = getGeneralRequest(req);

            check(dto);
            dto.setCompanyId(user.getCompanyId());

            GeneralRequestServicePrx generalRequestServicePrx = ServantUtils.getObject(GeneralRequestServicePrx.class);
            GeneralRequest generalRequest = generalRequestServicePrx.calculateRequestFlow(dto);
            logger.info("新版审批流:{}", generalRequest.getAllJudger());

            if (user.getCompanyId() == 12) {
				/*
				 特殊逻辑: 将老板多身份合并为老板的身份
				 */
                generalRequest.setAllJudger(mergeAdminMultiIdentity(generalRequest.getAllJudger(), user.getCompanyId()));
            }

            returnResponse(resp, generalRequest);
        } catch (Throwable e) {
            onThrowable(req, resp, e);
        }
    }

    /**
     * 去重老板身份
     *
     * @param allJudger
     * @return
     */
    private String mergeAdminMultiIdentity(String allJudger, Integer companyId) {
        logger.info("去重老板身份前:{} ", allJudger);
        try {
            UserServicePrx userService = ServantUtils.getObject(UserServicePrx.class);
            User admin = userService.getAdminUser(companyId);
            List<User> userList = userService.getUserListByContactIds(allJudger);
            userList = sortByString(userList, allJudger);

            List<Integer> contactIds = new ArrayList<>();
            for (User user : userList) {
                if (user.getIsAdminIdentity() > 0) {
                    contactIds.add(admin.getContactId());
                } else {
                    contactIds.add(user.getContactId());
                }
            }

            logger.info("去重老板身份后:{} ", ListHelper.list2string(contactIds));
            return ListHelper.list2string(contactIds);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
        }
        return allJudger;
    }

    /**
     * 记录顺序
     *
     * @param users
     * @param allJudger
     * @return
     */
    private List<User> sortByString(List<User> users, String allJudger) {
        List<User> list = new ArrayList<>();

        for (String s : allJudger.split(",")) {
            for (User user : users) {
                if (s.equals(user.getContactId().toString())) {
                    list.add(user);
                    break;
                }
            }
        }

        return list;
    }


    private void returnResponse(HttpServletResponse resp, GeneralRequest generalRequest) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", "0");
        jsonObject.put("res_info", "提交成功");
        jsonObject.put("item", generalRequest);

        logger.info(jsonObject.toJSONString());

        printJson(resp, jsonObject.toJSONString());
    }

    private GeneralRequest getGeneralRequest(HttpServletRequest req) throws IOException {
        String reqBody = getContent(req);
        logger.info("json参数值 {}", reqBody);

        GeneralRequest generalRequest;
        try {
            generalRequest = JSONObject.parseObject(reqBody, GeneralRequest.class);
        } catch (Exception e) {
            throw new RpcServerLogicalException(1, "请求参数格式错误");
        }
        return generalRequest;
    }


    private static String shiftQuitJudger(String allJudger, int companyId) {
        logger.info("过滤前:" + allJudger);
        try {
            UserServicePrx userService = ServantUtils.getObject(UserServicePrx.class);
            List<User> userList = userService.getUserListByContactIds(allJudger);

            List<Integer> contactIds = new ArrayList<>();
            for (String judgerContactId : allJudger.split(",")) {
                for (User user : userList) {
                    if (user.getContactId().toString().equals(judgerContactId)) {
                        contactIds.add(user.getContactId());
                    }
                }
            }

            // 全部离职了
            if (Utils.isEmpty(contactIds)) {
                return userService.getAdminUser(companyId).getContactId().toString();
            }

            logger.info("过滤后:" + ListHelper.list2string(contactIds));
            return ListHelper.list2string(contactIds);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
        }
        return allJudger;
    }

    protected void check(GeneralRequest generalRequest) {
        if (generalRequest.getApplicant() == 0) {
            throw new RpcServerLogicalException(1, "请求内容为空");
        }
        if (generalRequest.getProject() < 1) {
            throw new RpcServerLogicalException(1, "工程参数出错");
        }
    }

    private String remainLastItem(String string) {
        logger.info("去重前:{}", string);
        List<String> list = new ArrayList<>();
        List<String> originalItems = ListHelper.string2StringList(string);

        for (int i = 0; i < originalItems.size(); i++) {
            String item = originalItems.get(i);
            if (!hasSameItem(originalItems, i, item)) {
                list.add(item);
            }
        }
        logger.info("去重后:{}", ListHelper.list2string(list));
        return ListHelper.list2string(list);
    }

    private <T> boolean hasSameItem(List<T> items, int index, T item) {
        for (int j = index + 1; j < items.size(); j++) {
            if (item.equals(items.get(j))) {
                return true;
            }
        }
        return false;
    }

}
